import { reactive, computed } from 'vue';
import { loadThirdTempCodeApi } from '../api';
import { useRoute, useRouter } from 'vue-router';
import { accountLoginApi } from '../../app-login/api/login';
import { useGlobalStore } from '@/service/store/global-store';
import { omit } from '@jecloud/utils';
import LoginLogoUrl from '@/service/assets/images/login-logo.png';
import { Modal } from '@jecloud/utils';
/**
 * 三方登录守卫
 * @param {*} param0
 */
export function useThirdLogin() {
  const globalStore = useGlobalStore();
  const route = useRoute();
  const router = useRouter();
  const state = reactive({
    depts: [],
    account: '',
    url: '',
  });
  // 登录图标
  const loginLogoUrl = computed(() => {
    return globalStore.activeApp?.loginLogo || LoginLogoUrl;
  });

  const { meta, query } = route;
  const { tempCode } = query;

  // 三方登录信息
  loadThirdTempCodeApi(tempCode).then((data) => {
    Object.assign(state, data);
  });
  // 登录
  const doLogin = (dept) => {
    accountLoginApi({
      account: state.account,
      deptId: dept.id,
      code: tempCode,
    })
      .then((token) => {
        globalStore.setToken(token);
        // 功能组件
        if (meta.func) {
          router.push({ path: state.url, query: omit(query, ['tempCode']) });
        } else {
          uni.reLaunch({ url: state.url });
        }
      })
      .catch((data) => {
        Modal.alert(data.message);
      });
  };
  return { state, doLogin, loginLogoUrl };
}
